package com.ndhutu.ee.util.pay.pay96;

import com.alibaba.fastjson.JSONObject;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.MD5Util;
import com.ndhutu.ee.util.http.OKHttpUtil;
import com.ndhutu.ee.util.pay.Notify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 96支付工具类
 */
public class Pay96Util {
    private static Logger log = LoggerFactory.getLogger(Pay96Util.class);

    /**
     * 下单
     * @param config
     * @param orderNumber
     * @param amount
     * @param body
     * @return
     * @throws Exception
     */
    public static String order(Pay96Config config, String orderNumber, Integer amount, String body) throws Exception{
        Map<String, String> param = new HashMap<>();

        param.put("pay_memberid", config.getMemberid());
        param.put("pay_orderid", orderNumber);
        param.put("pay_applydate", DateUtil.getCurrTimeStr());
        param.put("pay_bankcode", "8");
        param.put("pay_notifyurl", config.getNotifyUrl());
        param.put("pay_callbackurl", config.getCallbackUrl());
        param.put("pay_amount", amount/100.0 + "");

        String stringSignTemp = OKHttpUtil.sortParam(param, false) + "&key="+config.getApiKey();
        String sign = MD5Util.encode32(stringSignTemp).toUpperCase();
        param.put("pay_md5sign", sign);
        param.put("pay_productname", body);
        param.put("pay_type", "2");

        String url = "http://www.96zzy01.com/Pay_Index.html";

        String result = OKHttpUtil.post(url, param);
        log.info("96支付下单返回结果："+result);

        return result;
    }

    /**
     * 获取回调请求参数
     * @param request
     * @return
     * @throws Exception
     */
    public static Map<String, String> getNotifyRequestParams(HttpServletRequest request) throws Exception{
        Map<String,String> params = new HashMap<String, String>();

        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info("96支付回调参数："+ JSONObject.toJSONString(params));

        return params;
    }

    /**
     * 校验回调请求
     * @param params    回调请求参数
     * @param config
     * @param notify
     * @return
     * @throws Exception
     */
    public static String verifyNotifyRequest(Map<String, String> params, Pay96Config config, Notify notify) throws Exception{
        //签名验证
        boolean flag = false;
        String orgSign = params.get("sign");
        params.remove("sign");
        params.remove("attach");
        String stringSignTemp = OKHttpUtil.sortParam(params, false) + "&key="+config.getApiKey();
        String sign = MD5Util.encode32(stringSignTemp).toUpperCase();
        if(sign.equals(orgSign)){
            flag = true;
        }

        if(flag){
            if("00".equals(params.get("returncode"))) {
                String orderNumber = params.get("orderid");
                Integer amount = (int) (Double.parseDouble(params.get("amount")) * 100);

                //统一回调
                notify.handleNotify(orderNumber, amount);
                log.info("订单" + orderNumber + "96支付回调成功");
            }
            return "OK";
        }else{
            return "failure";
        }
    }


    public static void main(String[] args) throws Exception {
        Pay96Config config = new Pay96Config() {
            @Override
            public String getMemberid() {
                return "201099753";
            }

            @Override
            public String getApiKey() {
                return "gq15mheijkm4k8ujoja18ejvotstr2a2";
            }

            @Override
            public String getNotifyUrl() {
                return "http://share.mm.ppmkf.com/pay/success_pay.html";
            }

            @Override
            public String getCallbackUrl() {
                return "http://test.mm.api.ppmkf.com/mm-api/wallet/zunPayNotify";
            }
        };

//        String result = order(config, "123", 10, "测试商品");
//        System.out.println(result);

        String json = "{\"transaction_id\":\"20201028155359559910\",\"amount\":\"28.0000\",\"datetime\":\"20201028161818\",\"orderid\":\"1603871679205312\",\"returncode\":\"00\",\"sign\":\"06AAED70870654D5E9285EF52554D094\",\"attach\":\"\",\"memberid\":\"201099753\"}";
        Map<String, String> params = JSONObject.parseObject(json, Map.class);
        verifyNotifyRequest(params, config, null);
    }
}
